module MapHelper

# don't forget endmapsetup
def startmapsetup
	@index = 0 if @index.nil? #set default
	output = '<script src="http://maps.google.com/maps?file=api&v=2&key=' + @program.gmapapi + '&sensor=false" type="text/javascript"></script>' + "\n"
	output += '<script type="text/javascript">'+"\n"
	output += <<daEND
var map;
var geoXml;

$(document).ready(function() { initialize(); });
$(window).unload( function () { GUnload(); });

var runnermarkers = [];
var incmarkers = [];
var landmarkmarkers = [];

function initialize() {
  if (GBrowserIsCompatible()) {
   
var points = [];

var marks = [];

map = loadmap();
daEND
end

def endmapsetup
	output = <<daEND

  } else alert("Sorry, but your web browser is not compatable with Google Maps");
}
                </script>
daEND
end

#need a endroute() too
def showroute(route)
#assumes map and points are defined
output = "
//Load KML file
GDownloadUrl(\"" + route.public_filename + "\", function(data, responseCode) {"
output = output + <<'daEND'
//Parse the kml data
var xml = GXml.parse(data);

//Locate the linestring node and pull out the coordinates
var path = xml.documentElement.getElementsByTagName("LineString");
for(i=0;i< path[0].childNodes.length;i++) {
	var node = path[0].childNodes[i];
	if(node.nodeName =="coordinates") {
		var coords = node.textContent;
		//IE fix
		if(!coords) coords = node.text;
		var pathPoints = coords.replace(/^\s*/, 
'').replace(/\s*$/,'').split(/\s+/);
		for(var i = 0; i < pathPoints.length; i++) {
			var dataPoints = pathPoints[i].split(',');
//Data is in the wrong order so need to swap lat\lon values
			points.push(new GLatLng(parseFloat(dataPoints[1])
,parseFloat(dataPoints[0])));
		}
	}
}
//start
var startIcon = new GIcon(G_DEFAULT_ICON);
startIcon.image = "/images/start.png";
startIcon.iconSize = new GSize(20,20);
map.addOverlay(new GMarker(points[0],{ icon:startIcon }));

points.reverse();

var polyline = new GPolyline(points, "#0000FF", 4);
map.addOverlay(polyline);
map.setCenter(polyline.getBounds().getCenter());
//finish
var finishIcon = new GIcon(G_DEFAULT_ICON);
finishIcon.image = "/images/finish.png"
finishIcon.iconSize = new GSize(20,20);
map.addOverlay(new GMarker(points[0],{ icon:finishIcon }));


daEND
return output
end

def endroute
	"\n});\n"
end

def preprunners(runners)
runners = [ runners ] unless (runners.respond_to?("each"))
output = ""
runners.each do |r|
if ((r.distance_cache - @index*26.2) < 26.2) and ((r.distance_cache-@index*26.2)>=0)
output += <<daEND
(function() {
	runnermark = new Object;
	runnermark.type = "runner";
daEND
output += "\trunnermark.dist = " + r.distance_along_route.to_s + "* 1609.344;\n"
output += "\trunnermark.icon = '/images/cr_runner.png';\n"
output += "\trunnermark.infowindow = '"+yield(r).to_s + "';\n"
output += "\trunnermark.name = '"+escape_javascript(h(r.first_name)+" "+h(r.last_name))+"';\n"
output += "\tmarks.push(runnermark);\n})();\n";
end
end
output
end

def prepinc(incentives)
incentives = [ incentives ] unless (incentives.respond_to?("each"))
output = ""
incentives.each do |i|
if ((i.goal - @index*26.2) < 26.2) and ((i.goal-@index*26.2)>0)
# use self-executing function for scoping
output += <<daEND
(function() {
	incmark = new Object;
	incmark.type = "incentive";
daEND
output += "\tincmark.dist = " + (i.goal-@index*26.2).to_s + "* 1609.344;\n"
output += "\tincmark.icon = '/images/cr_star.png';\n"
output += "\tincmark.infowindow = '"+yield(i).to_s + "';\n"
output += "\tincmark.name = '"+escape_javascript(h(i.reward))+"';\n"
output += "\tmarks.push(incmark);\n})();\n";
end
end
output
end

#show all Landmarks in landmarks,
#optionally use the first runner as bounds
def showlandmarks(landmarks,bounds=false)
output = ""
landmarks.each do |l|
if bounds
	output += 'if (Math.abs('+l.lat.to_s+' - runnermarkers[0].getLatLng().lat()) < 0.005 && Math.abs('+l.lng.to_s+' - runnermarkers[0].getLatLng().lng()) < 0.006)'
end
	output += "\n{\n"
	output += "var landicon = new GIcon(G_DEFAULT_ICON);\n"
	output += "landicon.image = \"/images/landmark.png\";\n"
	output += "landicon.iconSize = new GSize(25,25);\n"
	output += "var marker = new GMarker(new GLatLng("+l.lat.to_s+","+l.lng.to_s+"),{icon:landicon});\n"
	output += "marker.bindInfoWindowHtml('" + yield(l) + "');\n"
	output += "landmarkmarkers.push(marker);\n"
	output += "map.addOverlay(marker);\n}\n"
end
output
end

def landmarkdesc(l)
	pf = ""
	if(!l.size.blank?) then pf = image_tag(l.public_filename)+"<br/>" end
	'<b>'+escape_javascript(l.name)+'</b><br/>'+pf+escape_javascript(l.description).gsub(/\\n/,'<br/>')
end

end
